package org.hfy.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 日期转换配置类
 * 处理URL参数中字符串到LocalDate的转换
 * 
 * @author hfy
 * @version 1.0
 */
@Configuration
public class DateConversionConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToLocalDateConverter());
    }

    /**
     * 字符串转LocalDate转换器
     */
    public static class StringToLocalDateConverter implements Converter<String, LocalDate> {
        
        private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        
        @Override
        public LocalDate convert(String source) {
            if (source == null || source.trim().isEmpty()) {
                return null;
            }
            try {
                return LocalDate.parse(source, FORMATTER);
            } catch (Exception e) {
                throw new IllegalArgumentException("Invalid date format. Expected format: yyyy-MM-dd, but got: " + source);
            }
        }
    }
} 